package org.angelica.core.aop;

import lombok.extern.slf4j.Slf4j;
import org.angelica.core.annotation.TargetDataSource;
import org.angelica.core.datasource.DataSourceNames;
import org.angelica.core.datasource.DynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源切面处理
 * @author aizhimin
 */
@Aspect
@Component
@Order(0)
@Slf4j
public class DataSourceAspect {
    @Pointcut("@annotation(org.angelica.core.annotation.TargetDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        TargetDataSource ds = method.getAnnotation(TargetDataSource.class);
        if(ds == null){
            DynamicDataSource.setDataSource(DataSourceNames.RDS_DS);
            log.info("set datasource is " + DataSourceNames.RDS_DS);
        }else {
            DynamicDataSource.setDataSource(ds.value());
            log.info("set datasource is " + ds.value());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.info("clean datasource");
        }
    }
}
